package com.chb.authentication;

import com.chb.common.ResultCode;
import com.chb.dto.ResultDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @description: 登录失败执行策略
 * @author: CHB
 * @create: 2021-11-16 16:56
 **/
@Slf4j
public class RestfulExceptionHandler implements AccessDeniedHandler, AuthenticationEntryPoint {

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        response.getWriter().println(ResultDto.builder()
                .data(null)
                .success(false)
                .code(ResultCode.PERMISSION_DENIED.getCode())
                .message("没有权限")
                .build());
        response.getWriter().flush();
    }

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        response.getWriter().println(ResultDto.builder()
                .data(null)
                .success(false)
                .code(ResultCode.CLIENT_ERROR.getCode())
                .message("未登录")
                .build());
        response.getWriter().flush();
    }
}
